package com.echo.yixiaowu.feature.main.home.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.echo.yixiaowu.R
import com.echo.yixiaowu.feature.main.home.DraggableItem
import com.echo.yixiaowu.feature.main.home.HomeTabItem
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.json.Json


private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "sort_order")

class SortDataRepository(private val context: Context) {
    private val SORT_ORDER_KEY = stringPreferencesKey("sort_order")

    private val commonTabs = listOf(
        HomeTabItem(id = 11, title = "Cosplay"),
        HomeTabItem(id = 12, title = "风景"),
        HomeTabItem(id = 13, title = "动漫"),
        HomeTabItem(id = 14, title = "游戏"),
        HomeTabItem(id = 15, title = "插画"),
        HomeTabItem(id = 16, title = "汽车"),
    )

    private val defaultJson = Json.encodeToString(
        listOf(
            DraggableItem(
                id = 0,
                title = "王者荣耀",
                isSelect = false,
                background = R.color.teal_200,
                tabs = commonTabs
            ),
            DraggableItem(
                id = 1,
                title = "王者世界",
                isSelect = false,
                background = R.color.purple_500,
                tabs = commonTabs
            ),
            DraggableItem(
                id = 2,
                title = "鸣潮",
                isSelect = true,
                background = R.color.headColor,
                tabs = listOf(
                    HomeTabItem(id = 17, title = "角色攻略"),
                    HomeTabItem(id = 18, title = "声骸搭配"),
                    HomeTabItem(id = 19, title = "地图探索")
                )
            )
        )
    )

    val saveOrderFlow: Flow<List<DraggableItem>> = context.dataStore.data.map { preferences ->
        val jsonString = preferences[SORT_ORDER_KEY] ?: defaultJson
        Json.decodeFromString<List<DraggableItem>>(jsonString)
    }

    suspend fun saveOrder(items: List<DraggableItem>) {
        val jsonString = Json.encodeToString(items)
        context.dataStore.edit { preferences -> preferences[SORT_ORDER_KEY] = jsonString }
    }

    suspend fun clearOrder() {
        context.dataStore.edit { preferences ->
            preferences.remove(SORT_ORDER_KEY)
        }
    }
}